package com.example.testmvc.service.impl;

import com.example.testmvc.mapper.UserMapper;
import com.example.testmvc.pojo.User;
import com.example.testmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * @author Cavan
 * @date 2023-06-01
 * @qq 2069543852
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //注册用户
    @Override
    public void register(User user) {
        //1.根据学号id查询数据库中是否存在用户
        User userById = userMapper.findByUserId(user.getId());
        //2.若存在则注册失败
        if (!ObjectUtils.isEmpty(userById)) throw new RuntimeException("学号id已存在！");
        //3.若不存在，进行注册
        userMapper.insert(user);
    }

    //用户登录
    @Override
    public User login(String id, String password) {
        //1.根据学号id查询用户
        User user = userMapper.findByUserId(id);
        //2.如果userById为空，则登陆失败
        if (ObjectUtils.isEmpty(user)) throw new  RuntimeException("用户名不存在！");
        //3.如果user不为空，则进行比较密码,如果查到的用户密码跟传过来的参数password密码相等则登录成功，否则登录失败
        if (!user.getPassword().equals(password)) throw new RuntimeException("密码错误！");
        return user;
    }

}
